/*
 * Copyright (c) 2019 Wormpex.com. All Rights Reserved.
 */

package com.sk.agent.javaag;

import jdk.internal.org.objectweb.asm.ClassReader;
import jdk.internal.org.objectweb.asm.ClassWriter;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;


/**
 * 讲
 *
 *
 * @author ke.su date: 2019-11-12 Time: 上午11:52
 */
public class PreMainAddTimeStatAgent {

    public static void premain(String agentArgs, Instrumentation instrumentation) {
        System.out.println("agentArgs:" + agentArgs);

        instrumentation.addTransformer(new ClassFileTransformer() {
            @Override
            public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

                if (className.contains("com/sk/agent/Account")) {
                    System.out.println("meet " + className);
                    ClassReader cr = new ClassReader(classfileBuffer);
                    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);

                    TimeStatClassAdapter classAdapter = new TimeStatClassAdapter(cw);
                    cr.accept(classAdapter, ClassReader.SKIP_DEBUG);

                    return cw.toByteArray();
                } else {
                    System.out.println(className);
                    return classfileBuffer;
                }


            }
        }, true);

    }
}
